/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Feb 23, 2012  10:34:35 AM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.mm.outbound
 * File Name : PsWbsMasterService.java
 * TODO
 */
package sap.business.ps.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.PsWbsMaster;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.PsWbsMasterServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;

import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class PsWbsMasterService extends SynchroOutAbstract {
	
	private static final Logger log = Logger.getLogger(PsWbsMasterService.class);	
	private static PsWbsMasterServices psWbsMasterServices = null;

	/**
	 * 
	 */
	public PsWbsMasterService() {
		// TODO Auto-generated constructor stub
		try {
			
			this.sap_bapi = "ZIN_PSMAS_WBS";
			this.sap_table = "WBS_DATA";
			this.sap_table_return = "RETURN";
			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}	
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub		
		
		//Check Is not isEmpty is exit method.
		if(!jcoTable.isEmpty())
		{
			log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
			return;
		}		
		
		if(!CommonService.IsNull(value_list)){
			log.info("value_list.size : " + value_list.size());			
			log.info("table.getNumRows : " + jcoTable.getNumRows());
			
			for (Object obj : value_list) 
	        {				
				PsWbsMaster model = (PsWbsMaster)obj;
				log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId());
				
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
				
				jcoTable.setValue("POST1", model.getUnitNumber());
				jcoTable.setValue("WERKS", model.getSapPlantCode());
				jcoTable.setValue("VERNR", "");
				jcoTable.setValue("WBSLV1", model.getBuildingPhase());
				jcoTable.setValue("WBSLV1_DESC", model.getBuildingPhaseName());
				jcoTable.setValue("WBSLV2", model.getZoneCode());
				jcoTable.setValue("WBSLV2_DESC", model.getZoneCodeName());
				jcoTable.setValue("ASTNR", "");
				jcoTable.setValue("PROPTYP", model.getPropertyTypeCode());  
				jcoTable.setValue("UNITTYP", model.getProductCode());
				jcoTable.setValue("USR01", model.getModelsCode());
				
				if(!CommonService.IsNull(model.getModelSubRevision()))
					jcoTable.setValue("USR02", model.getModelRevision() + "/" + model.getModelSubRevision());
				else
					jcoTable.setValue("USR02", model.getModelRevision());
				
				jcoTable.setValue("USR10", model.getConsStatus());				
				jcoTable.setValue("SUB_PROJ", model.getPhaseCode());
				jcoTable.setValue("USR03", model.getHomeNo());
				
				if(model.getRoomArea() != null)
					jcoTable.setValue("AREA1", model.getActualSalesArea() +"");
				
				if(model.getFinalArea() != null)
					jcoTable.setValue("AREA2", model.getFinalArea()+"");
				
				jcoTable.setValue("USRSTAT", model.getSalesStatus());
	        }
		}	
		
		//jcoFunction.execute(jco_conn.getJCoConnection());

		super.SynchroToSap(jcoFunction, jcoTable, value_list);
	}
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		
		List<PsWbsMaster> lst = new ArrayList<PsWbsMaster>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				PsWbsMaster model = psWbsMasterServices.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				log.info(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					lst.add(model);
				}
			}
			
			psWbsMasterServices.Updated(lst);
		}else
			log.info(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<PsWbsMaster> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<PsWbsMaster> newlst = new ArrayList<PsWbsMaster>();
				for(PsWbsMaster model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				 new PsWbsMasterServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	/**
	 * 
	 * @param company
	 * @param project
	 * @param buildingPhase
	 * @param floorZone
	 * @param unitNumber
	 * @param instanceNo
	 * @param issync
	 * @throws Exception
	 */
	public void SendingToSAP(String company, String project, String buildingPhase, String floorZone, String unitNumber, String instanceNo, String issync) throws Exception
	{
		log.info("SendingToSAP Start. ");
		List<PsWbsMaster> value_list = null;
		try{
			
			this.jco_conn  = new Connection();
			
			//Get SAP BAPI function
			JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
			
			//Get SAP Staging table
			JCoTable jcoTable = jco_conn.getTables(sap_table);
			psWbsMasterServices = new PsWbsMasterServices(this.emSynchro);
			value_list = psWbsMasterServices.findByUnitNumber1(company, project, buildingPhase, floorZone, unitNumber, instanceNo, issync);
			
			if(!CommonService.IsNull(value_list)){
				SynchroToSap(jcoFunction, jcoTable, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);	
			}else
				log.warn(" findByUnitNumber find not found ");
			
		}catch(Exception e)
		{
			UpdateStagingWhenError(value_list, e);
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * 
	 * @param value_list
	 * @throws Exception
	 */
	public void SendingToSAP(List<PsWbsMaster> value_list) throws Exception
	{
		log.info(" Start SendingToSAP. ");
		try{
			if(!CommonService.IsNull(value_list))
			{
				this.jco_conn  = new Connection();
				
				//Get SAP BAPI function
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				psWbsMasterServices = new PsWbsMasterServices(this.emSynchro);
			
				//Send to SAP
				SynchroToSap(jcoFunction, jcoTable, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);	
			}else
				log.warn(" findByUnitNumber find not found ");
			
		}catch(Exception e)
		{
			UpdateStagingWhenError(value_list, e);
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	@Deprecated
	private void Start() throws Exception
	{
		
		this.jco_conn  = new Connection();

		//Get SAP BAPI function
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		psWbsMasterServices = new PsWbsMasterServices(this.emSynchro);
		List<PsWbsMaster> value_list = psWbsMasterServices.findIsSync("N");	
		SynchroToSap(jcoFunction, jcoTable, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);		
	}
	
//	public static void main(String [] agrs){
//		try {
//			
//			PsWbsMasterService xx = new PsWbsMasterService();
//			
//			xx.Start();
//			
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			log.error(e);
//			e.printStackTrace();
//		}
//	}

}
